from django.shortcuts import render
from exam.models import *
#from service.views import render_md
import markdown
# Create your views here.


def render_md(md: str):
    """渲染markdown"""
    html = markdown.markdown(
        md,
        extensions=[
            "markdown.extensions.extra",  # 额外插件
            "markdown.extensions.codehilite",  # 代码高亮
            "markdown.extensions.fenced_code",  # 代码格式化
            "markdown.extensions.toc",  # 目录
            "markdown.extensions.tables",  # 表格
            "markdown.extensions.attr_list",
            "mdx_math",
            "markdown.extensions.def_list",
            "markdown_katex",

        ],
        extension_configs={
            "mdx_math": {
                "enable_dollar_delimiter": True,  # 是否启用单美元符号（默认只启用双美元）
                "add_preview": True,  # 在公式加载成功前是否启用预览（默认不启用）
            },
            'markdown_katex': {
                'no_inline_svg': True,      # fix for WeasyPrint
                'insert_fonts_css': True,
            },
        },
    )

    return html
def exam(request):
    print("exam is called!")
    return render(request, 'exam.html')
    #return request('exam.html')

def exam_paper(request):
    print("exam_paper is called!")
    #获取所有的question
    questions = Question.objects.all().values()
    print("questions: ",questions)
    #tempQuestions=Question.objects.all()
    #tempQ=render_md(tempQuestions[0].question)
    #print("tempQ: ",tempQ)
    questions_list = list(questions)
    #根据questions的type进行分类
    questions_dict = {}
    for question in questions_list:
        #print(question)
        if question["question_type"] not in questions_dict:
            questions_dict[question["question_type"]] = []
        #print("question:",question["question"])
        
        question["question"]=render_md(question["question"])
        
        questions_dict[question["question_type"]].append(question)
    #将questions_dict放入exam_paper.html中
    #return render(request, 'exam_paper.html')
    print("questions_dict: ", questions_dict)
    return render(request, 'exam_paper.html', {'questions': questions_dict})